package thread.thread_04_20.concurrent_sort;

import java.util.Arrays;

/**
 * @author Stark
 * @description 实现并发的排序
 * @date 2022/4/21 16:24
 **/
public class ConcurrentSort {
    static class SortWorker extends Thread{
        private final long[] array;
        private final int fromIndex;
        private final int toIndex;

        // 利用构造方法，将待排序的数组区间情况，传入
        // 对 array 的 [fromIndex, toIndex) 进行排序
        public SortWorker(long[] array,int fromIndex,int toIndex){
            this.array = array;
            this.fromIndex = fromIndex;
            this.toIndex = toIndex;
        }

        @Override
        public void run() {
            Arrays.sort(array,fromIndex,toIndex);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        long[] array = ArrayHelper.generateArray(4_000_0000);

        long start = System.currentTimeMillis();

        SortWorker s1 = new SortWorker(array,0,1_000_0000);
        s1.start();// 让 s1 进入就绪队列
        SortWorker s2 = new SortWorker(array,1_000_0001,2_000_0000);
        s2.start();// 让 s2 进入就绪队列
        SortWorker s3 = new SortWorker(array,2_000_0000,3_000_0000);
        s3.start();// 让 s3 进入就绪队列
        SortWorker s4 = new SortWorker(array,3_000_0000,4_000_0000);
        s4.start();// 让 s4 进入就绪队列

        // 等待 4 个线程全部排序完毕，这 4 个 join 没有前后顺序
        s1.join();
        s2.join();
        s3.join();
        s4.join();

        // 4 个线程一定全部结束了
        // TODO：进行 4 路归并，将 4 个有序数组，归并成一个有序数组
        long end = System.currentTimeMillis();

        System.out.println("并发排序用时：" + (end - start) + "ms");
    }
}
